package com.bulletelc.apollopre.framework;

import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.bulletelc.apollopre.interfaces.listener.PermissionListener;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.ArrayList;
import java.util.List;

import static com.bulletelc.apollopre.constants.GlobalConfig.REQUEST_PERMISSION;


/**
 * author: lhl
 * time  : 2017/10/15
 * desc  : Activity的基类
 */

public abstract class BaseActivity extends AutoLayoutActivity implements BaseInterface {
    private List<String> permissionList;
    private PermissionListener listener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        doBeforeSetContentView();
        setContentView(getLayoutRes());
        adjustLayout();
        assignViews();
        setListener();
        initData(savedInstanceState);

    }

    /**
     * 在setContentView()方法前进行一些设置
     */
    protected  void doBeforeSetContentView(){
        //对Activty进行统一的管理，将Activity放到堆栈中进行管理(暂时不考虑activity的管理)
        //ActivityInAppToManager.getAppManager().addActivity(this);

        //设置presenter
        setPresenter();

        //设置全屏
        setFullScreen();

        //设置屏幕的方向，默认
        setScreenOrientation(true);

        //设置状态栏
        setStatusBar();
    }

    protected void adjustLayout() {
        ViewGroup contentFrameLayout = findViewById(Window.ID_ANDROID_CONTENT);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            parentView.setFitsSystemWindows(true);
        }
    }

    /**
     * 初始化presenter,钩子方法
     */
    protected void setPresenter() {
    }

    /**
     * 设置全屏,此为钩子方法
     */
    protected void setFullScreen() {
    }


    /**
     * 设置屏幕默认的方向，此为钩子方法,
     * @param isImmobilizationScreen 是否固定屏幕，true:屏幕固定（横竖屏不能切换），false:根据传感器切换横竖屏
     */
    protected void setScreenOrientation(boolean isImmobilizationScreen) {
        if (isImmobilizationScreen) {
            //默认设置竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    /**
     *设置状态栏的颜色（默认颜色）（4.4以上系统有效）
     * 此为钩子方法，可重写设置其他颜色或设置类型为沉浸式状态栏或者设置为没有状态栏
     * 如果使用重写的话，可用StatusBarCompatUtils工具类进行重写
     */
    protected void setStatusBar(){
        // 系统 6.0 以上 状态栏白底黑字的实现方法
        this.getWindow()
                .getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    /**
     * 初始化Toolbar
     * @param toolbar
     * @param title
     */
    protected final void initToolBar(Toolbar toolbar, String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
    }

    /**
     * 初始化Toolbar
     * @param toolbar
     * @param resID 字符串资源ID
     */
    protected final void initToolbar(Toolbar toolbar, int resID) {
        initToolBar(toolbar,getResources().getString(resID));
    }

    /**
     * 查找子控件，可省类型强转装换
     * @param id
     * @param <T>
     * @return
     */
    protected final <T extends View> T findView(int id){
        T view = (T) findViewById(id);
        return view;
    }



    /**
     * Android6.0运行时权限封装
     *
     * 申请的权限属于危险权限的话,必须调用此方法,在接口回调中 do something
     *
     */
    public void requestRuntimePermission(String[] permissions, PermissionListener listener) {
        this.listener = listener;
        permissionList = new ArrayList<>();
        for (int i = 0, length = permissions.length; i < length; i++) {
            String permission = permissions[i];
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this,permissionList.toArray(new String[permissionList.size()]), REQUEST_PERMISSION);
        }else{
            if (listener != null) {
                listener.onGranted();
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //6.0运行时权限封装
            case REQUEST_PERMISSION:
                int length = grantResults.length;
                if (length>0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i=0;i<length;i++){
                        int grantResult=grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissions.add(permission);
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        listener.onGranted();
                    } else {
                        listener.onDenied(deniedPermissions);
                    }
                }

                break;
            default:
                break;
        }


    }


}
